package com.upper.service.nginxset;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.lucksyc.utilindependent.resultview.core.data.ViewData;
import org.lucksyc.utilindependent.resultview.seed.deal.ViewBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.componentbean.UserNginxSet;
import com.template.NginxConfig;
import com.util.Util;

@Service
public class NginxSetInterfaceImpl implements NginxSetInterface {
	
	private static final Logger log = LoggerFactory.getLogger(NginxSetInterfaceImpl.class);
	
	@Autowired
	ViewBuilder viewBuilder;
	
	@Autowired
	UserNginxSet userset;
	
	@Autowired
	NginxConfig nginxConfig;
	
	@Autowired
	ResourceLoader resourceLoader;
	
	@Override
	public ViewData uploadjson(MultipartFile file, boolean isMine) {
		byte[] bs = null;
		try {
			bs = file.getBytes();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (null == bs) {
			return viewBuilder.wrapError("不支持解析文件！", 12101);
		}
		String content = new String(bs);
		UserNginxSet userBean = Util.toBean(content, UserNginxSet.class);
		boolean status = userset.copy(userBean);
		if (status) {
			log.info("ConfigInterfaceImpl:uploadjson:updateAllMessage.");
			return viewBuilder.wrap(true);
		} else {
			return viewBuilder.wrapError("解析失败", 12101);
		}
	}
	
	@Override
	public void downloadjson(HttpServletResponse response) {
		String fileName = LocalDateTime.now().withNano(0)+".json";
		try (	
				OutputStream out = response.getOutputStream();
			) {
			String json = Util.toJson(userset);
			/**
			 *  
			 */
			String encodingName= URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString());
			response.setContentType("text/json");
			response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
			response.addHeader("charset", "utf-8");
			response.addHeader("Pragma", "no-cache");
			response.setHeader("Content-Disposition", "attachment; filename=\"" + encodingName+ "\"; filename*=utf-8''"+ encodingName);
			out.write(json.getBytes());
		    out.flush();
		} catch (Exception ex) {
			
		}
	}
	
	@Override
	public void downloadtable(HttpServletResponse response) {
		String fileName = LocalDateTime.now().withNano(0)+".txt";
		List<String> content = nginxConfig.getTableMsg();
		if (null== content) {
			return;
		}
		try (	
				OutputStream out = response.getOutputStream();
			) {
			String encodingName= URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString());
			response.setContentType("text/txt");
			response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
			response.addHeader("charset", "utf-8");
			response.addHeader("Pragma", "no-cache");
			response.setHeader("Content-Disposition", "attachment; filename=\"" + encodingName+ "\"; filename*=utf-8''"+ encodingName);
			Iterator<String> it = content.iterator();
			String newLine = System.getProperty("line.separator");
			while (it.hasNext()) {
				out.write(it.next().getBytes());
				out.write(newLine.getBytes());
			}
		    out.flush();
		} catch (Exception ex) {
			
		}
	}
	
	@Override
	public void downloadconf(HttpServletResponse response, boolean isBs) {
		String fileName = "nginx.txt";
		List<String> content = nginxConfig.getContent(isBs);
		if (null== content) {
			return;
		}
		try (	
				OutputStream out = response.getOutputStream();
			) {
			/**
			 *  
			 */
			String encodingName= URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString());
			response.setContentType("text/txt");
			response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
			response.addHeader("charset", "utf-8");
			response.addHeader("Pragma", "no-cache");
			response.setHeader("Content-Disposition", "attachment; filename=\"" + encodingName+ "\"; filename*=utf-8''"+ encodingName);
			Iterator<String> it = content.iterator();
			String newLine = System.getProperty("line.separator");
			while (it.hasNext()) {
				out.write(it.next().getBytes());
				out.write(newLine.getBytes());
			}
		    out.flush();
		} catch (Exception ex) {
		}
	}
	
	@Override
	public void downloadorgconf(HttpServletResponse response) {
		String fileName = "nginx.conf";
		try (
				InputStream inputStream = resourceLoader.getResource("classpath:templates/" + Paths.get(fileName).toString()).getInputStream();
				ServletOutputStream servletOutputStream = response.getOutputStream();
			) {
			String encodingName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString());
			Path path= Paths.get(fileName);
			
			response.setContentType(Files.probeContentType(path));
			response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
			response.addHeader("charset", "utf-8");
			response.addHeader("Pragma", "no-cache");
			response.setHeader("Content-Disposition", "attachment; filename=\"" + encodingName+ "\"; filename*=utf-8''" + encodingName);
			IOUtils.copy(inputStream, servletOutputStream);
			response.flushBuffer();
		} catch (Exception e) {
		}
	}

}
